package com.sangeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sangeng.domain.LoginUser;
import com.sangeng.entity.User;
import com.sangeng.exception.UserCheckException;
import com.sangeng.mapper.MenuMapper;
import com.sangeng.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author: xujiabing
 * @date: 2024-09-13 16:13
 * @description 实现UserDetailsService接口，重写方法,从数据库中查询用户信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 查询登录用户信息
     * @param username 登录用户
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.查询用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper =
                new LambdaQueryWrapper<User>()
                        .eq(User::getUserName, username);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        //user为空处理
        if (Objects.isNull(user)) {
            throw new UserCheckException("用户名或密码错误");
        }
        //2.查询用户对应的权限信息
        //查询用户的权限信息,添加到LoginUser中
        //模拟用户权限信息,后续改成数据库
        //List<String> list = new ArrayList<>(Arrays.asList("admin","test"));

        List<String> perms = menuMapper.selectPermsByUserId(user.getId());
        return new LoginUser(user,perms);
    }
}
